const express = require('express');
const cors = require('cors');
const axios = require('axios');
const cheerio = require('cheerio');

const app = express();
const PORT = 9527;

// 启用 CORS
app.use(cors());

function isSameDay(date1, date2) {
  return (
    date1.getFullYear() === date2.getFullYear() &&
    date1.getMonth() === date2.getMonth() &&
    date1.getDate() === date2.getDate()
  );
}

function extractContributionData(str) {
  // 正则表达式匹配模式
  const pattern = /^(\d+)个贡献：(\d{4}-\d{2}-\d{2})$/;
  const match = str.match(pattern);

  if (match) {
    return {
      count: parseInt(match[1], 10),
      date: match[2],
    };
  } else {
    return null;
  }
}

const cache = {
  data: null,
  lastUpdated: null,
};
app.get('/gitee-contribution', async (_, res) => {
  try {
    const now = new Date();
    if (cache.data && cache.lastUpdated && isSameDay(cache.lastUpdated, now)) {
      console.log('读取缓存');
      return res.json(cache.data);
    }

    const url = 'https://gitee.com/du-dudu';

    const response = await axios.get(url);
    const html = response.data;

    const $ = cheerio.load(html);

    const boxList = $('.contribution-box .right-side .box');
    if (boxList.length === 0) {
      console.log('未找到 .contribution-box .right-side .box');
      return;
    }
    // 提取 boxList 中的所有 data-content 的值
    const dataContents = boxList
      .map((index, element) => {
        return $(element).attr('data-content');
      })
      .get();

    const result = dataContents
      .map((data) => {
        return extractContributionData(data);
      })
      .filter((data) => data !== null);

    cache.data = result;
    cache.lastUpdated = now;
    console.log('更新缓存');

    res.json(result);
  } catch (error) {
    res.json([]);
  }
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
